#!/usr/bin/env groovy

def call(String techStack = '') {    
     echo "======================SAVE ARTIFACTS (TECHSTACK:${techStack})============================="
     try
     {
        if ( techStack == 'vue') {
        sh label: 'DOCKER-SAVE', returnStdout: true, script: 
        '''
        echo "save image: ${HARBOR}/${PROJECT_NAME}/${DOCKER_NAME}:${VERSION_NUMBER}"
        if [ ! -d $PWD/target ]; then
            mkdir $PWD/target
        fi
        docker save ${HARBOR}/${PROJECT_NAME}/${DOCKER_NAME}:${VERSION_NUMBER} -o $PWD/target/${DOCKER_NAME}_${VERSION_NUMBER}.tar
  
        '''        
    } else if (techStack == 'springboot') { 
        sh label: 'DOCKERCOMPOSE-SAVE', returnStdout: true, script: 
        '''
        echo "save image: ${HARBOR}/${PROJECT_NAME}/${DOCKER_NAME}:${VERSION_NUMBER}"         
        if [ ! -d $PWD/target ]; then
            mkdir $PWD/target
        fi

        IDS=$(docker images|grep -v none| grep ^${HARBOR}/${PROJECT_NAME}/|grep ${VERSION_NUMBER} |awk \'{print $1":"$2}\')
        echo "$IDS"
        docker save $IDS -o $PWD/target/${DOCKER_NAME}_${VERSION_NUMBER}.tar
        '''       

    }else {
        throw new RuntimeException("NotImplementedException; ${techStack} IS NOT SUPPORT NOW")
     }

    archiveArtifacts artifacts:"target/${DOCKER_NAME}_${VERSION_NUMBER}.tar", fingerprint: true

    sh label: 'Clean up regularly', returnStdout: true, script: 
        '''
        cd $PWD/target
        total_file_num=`ls -l | grep -v 'total'| wc -l`
        if [ $total_file_num -gt 10 ];
        then
            num=`expr $total_file_num - 10`
            files=`ls -ltr | grep -v 'total' | awk '{print $9}' | head -n $num`
            echo $files | xargs rm -f
            echo "保留10个备份，删除早期备份: " $files
        fi
        '''   
 } 
    catch(Exception ex) {
         println("Catching the exception,");
         println(ex.toString());
         println(ex.getMessage());
         println(ex.getStackTrace());  
      }
      echo "===============================SAVE ARTIFACTS DONE=============================="    
}
